/*
 * main.c
 * 
 * Freecut firmware, main program
 *
 *
 * Copyright 2010 <freecutfirmware@gmail.com> 
 *
 * This file is part of Freecut.
 *
 * Freecut is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2.
 *
 * Freecut is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Freecut. If not, see http://www.gnu.org/licenses/.
 *
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <inttypes.h>
#include <stdio.h>
#include "usb.h"
#include "keypad.h"
#include "lcd.h"
#include "timer.h"
#include "stepper.h"
#include "cli.h"
#include "flash.h"
#include "version.h"
#include "dial.h"

static FILE usb = FDEV_SETUP_STREAM( usb_putchar, usb_getchar, _FDEV_SETUP_RW );

#define LOAD_PAPER	0x4c
#define UNLOAD_PAPER	0x4d

void poll_keypad( void )
{
    int key = keypad_scan( );

    switch( key )
    {
		case LOAD_PAPER:
			stepper_load_paper();
			break;

		case UNLOAD_PAPER:
			stepper_unload_paper();
			break;
		
		case 0x48:
			keypad_set_leds( 0x0001);
			break;
		
		case 0x4b:
			keypad_set_leds( 0);
			break;
			
		
		default:
		if( key >= 0 )
		{
			beeper_on( 2400 );
			msleep( 20 );
			wdt_reset( );
			printf( "# unknown key %02x\n", key );
			beeper_off( );
		}
	}
}

int main( void )
{
	// Watchdog is to be disabled in the fuse bits.
   //  wdt_enable( WDTO_30MS );
    usb_init( );
    timer_init( );		// init timers first steppers rely on timers 
    stepper_init( );
	keypad_init( );
    sei( );
    lcd_init( );
    
 //   flash_init( );
    // dial_init( ); Dials Speed and Pressure are analog potentiometers -- Dial Size is a quadrature encoder -- 
	// none of the dials are currently used in the code 

    //wdt_reset( );

    // short blip to show we're awake
  
    beeper_on( 1760 );
	msleep( 30 );	
	//wdt_reset( );
	beeper_off( );
    beeper_on( 2000 );
    msleep( 30 );
	//wdt_reset( );
    beeper_off( );	

	//connect stdout to USB port
	stdout = &usb;
	version();

    fprintf( &lcd, "\fCutFree\n%s", VERSION);
    while( 1 )
    {
        cli_poll( );
		wdt_reset( );
		if( flag_25Hz )
		{
			flag_25Hz = 0;
			// Dial data is not used -- speed and pressure are only set by USB interface 
			// dial_poll( );	
			poll_keypad( );
		}
		if( flag_Hz )
		{
			flag_Hz = 0;
		}
    }
}
